14. Quiz: Dictionaries and Identity Operators
Quiz: Define a Dictionary
Define a dictionary named population
that contains this data:
Keys | Values |
---|---|
Shanghai | 17.8 |
Istanbul | 13.3 |
Karachi | 13.0 |
Mumbai | 12.5 |
Start Quiz:
# Define a Dictionary, population,
# that provides information
# on the world's largest cities.
# The key is the name of a city
# (a string), and the associated
# value is its population in
# millions of people.
# Key | Value
# Shanghai | 17.8
# Istanbul | 13.3
# Karachi | 13.0
# Mumbai | 12.5
Immutable Keys
SOLUTION:
- `str`
- `int`
- `float`
Quiz: Looking Up What Isn't There
SOLUTION:
A `KeyError` occursget
with a Default Value
Dictionaries have a related method that's also useful, get()
. get()
looks up values in a dictionary, but unlike looking up values with square brackets, get()
returns None
(or a default value of your choice) if the key isn't found. If you expect lookups to sometimes fail, get()
might be a better tool than normal square bracket lookups.
>>> elements.get('dilithium')
None
>>> elements['dilithium']
KeyError: 'dilithium'
>>> elements.get('kryptonite', 'There\'s no such element!')
"There's no such element!"
In the last example we specified a default value (the string 'There's no such element!') to be returned instead of None
when the key is not found.
Checking for Equality vs. Identity: ==
vs. is
Checking for Equality vs. Identity
SOLUTION:
True, True, True, FalseStart Quiz:
# Test the code here if you'd like
a = [1, 2, 3]
b = a
c = [1, 2, 3]